package com.ironman.analyze.core.handler;

import com.ironman.analyze.core.compute.entity.HeartrateWindowData;
import com.ironman.common.params.HeartrateParam;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.function.Consumer;

@Slf4j
public class HeartratePostHandler extends BasePostHandler<HeartrateWindowData> {

    private Double preHeartrate = null;

    private final HeartrateParam heartrateParam;

    public HeartratePostHandler(HeartrateParam heartrateParam) {
        this.heartrateParam = heartrateParam;
    }

    @Override
    public void handler(HeartrateWindowData data, Consumer<HeartrateWindowData> consumer) {
        doHandler(data, consumer);
    }

    @Override
    public void threshold(HeartrateWindowData data) {
        Double heartbeat = data.getHeartrate();
        if (Objects.isNull(heartbeat)) {
            return;
        }

        if (preHeartrate == null) {
            getCounter().incrementAndGet();
            preHeartrate = heartbeat;
            return;
        }

        Integer heartrateThreshold = heartrateParam.getHeartrateThreshold();
        double diffHeartrate = Math.abs(heartbeat - preHeartrate);
        if (diffHeartrate > heartrateThreshold) {
            getCounter().set(0);
            log.debug("主心率触发对比阈值:{} 当前:{} 前一个:{} 相差:{} ", heartrateThreshold, heartbeat, preHeartrate, diffHeartrate);
            preHeartrate = heartbeat;
            return;
        }

        Integer countThreshold = heartrateParam.getCountThreshold();
        if (getCounter().incrementAndGet() >= countThreshold) {
            getCounter().set(0);
            log.debug("心率触发数量阈值:{} ", countThreshold);
            preHeartrate = heartbeat;
            return;
        }
        data.setHeartrate(preHeartrate);
    }

}
